package com.itzb.asone.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class CommonUtils {

	/**
	 * 移除图片标签
	 * @param result
	 * @return
	 */
	public static String replaceImg(String result) {
		String regxpForImgTag = "<img\\s[^>]+/>";
		Pattern pattern = Pattern.compile(regxpForImgTag);
		Matcher matcher = pattern.matcher(result);
		while (matcher.find()) {
		    String temp = matcher.group();
		    String tempUrl = temp.substring(temp.indexOf("src=") + 5);
		    tempUrl =tempUrl.substring(0, tempUrl.indexOf("\""));
		    result = result.replace(temp, "");
		}

		return result;
	}
	
	/**
	 * 获取第一张图片标签
	 * @param result
	 * @return
	 */
	public static String foundFirstImg(String result){
		String regxpForImgTag = "<img\\s[^>]+/>";
		Pattern pattern = Pattern.compile(regxpForImgTag);
		Matcher matcher = pattern.matcher(result);
		if (matcher.find()) {
			return matcher.group();
		} else {
			return null;
		}
	}
	
	/**
	 * 删除所有HTML标签
	 * @param htmlStr
	 * @return
	 */
	public static String getTextFromTHML(String htmlStr) {
		Document doc = Jsoup.parse(htmlStr);
		String text = doc.text();
		// remove extra white space
		StringBuilder builder = new StringBuilder(text);
		int index = 0;
		while (builder.length() > index) {
			char tmp = builder.charAt(index);
			if (Character.isSpaceChar(tmp) || Character.isWhitespace(tmp)) {
				builder.setCharAt(index, ' ');
			}
			index++;
		}
		text = builder.toString().replaceAll(" +", " ").trim();
		return text;
	}

}
